package javaNIO1.channel;


import java.io.FileOutputStream;

import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.nio.channels.Channels;
import java.nio.channels.FileChannel;
import java.nio.channels.ReadableByteChannel;
import java.nio.channels.WritableByteChannel;
import java.util.LinkedList;
import java.util.List;
import java.util.Optional;
import java.util.Random;

/**
 * Created with Intel IDEA.
 * 矢量IO
 * Scatter: 从缓冲区读取数据并按顺序散布到多个缓冲区中，直到缓冲区满或这通道数据读取完毕。
 * Gather: 从多个缓冲区中按顺序抽取数据并沿着通道发送
 *
 *  模拟gather 操作
 * @Auther: gjt
 * @Date: 2024/7/14 9:51
 */
public class SGIO {
    private static final String path = "C:\\Users\\23152\\Desktop\\hello.txt";
    private static final Random rand = new Random();
    private static String newline = "line.separator";
    private static String[] col1 = {"a", "b", "c", "d", "e", "f", "g"};
    private static String[] col2 = {"h", "i", "j", "k", "l", "m", "n"};
    private static String[] col3 = {"o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"};


    public static void main(String[] args) throws Exception {
        int reps = 3;
        if (args.length > 0) {
            reps = Integer.parseInt(args[0]);
        }

        FileOutputStream fileOutputStream = new FileOutputStream(path);
        FileChannel channel = fileOutputStream.getChannel();
        ByteBuffer[] buffers = utterBs(reps);
        while (channel.write(buffers) > 0) {
            // 文件通道对象是线程是安全的
//            channel.read();
        }
        System.out.println("输出");
        fileOutputStream.close();
    }

    private static ByteBuffer[] utterBs(int count) throws Exception {
        List linkedList = new LinkedList();

        for (int i = 0; i < count; i++) {
            linkedList.add(pickRandom(col1, " "));
            linkedList.add(pickRandom(col2, " "));
            linkedList.add(pickRandom(col3, newline));
        }

        ByteBuffer[] buffers = new ByteBuffer[linkedList.size()];
        linkedList.toArray(buffers);
        return buffers;
    }

    private static ByteBuffer pickRandom(String[] strings, String suffix) throws UnsupportedEncodingException {
        String string = strings[rand.nextInt(strings.length)];
        int total = string.length() + suffix.length();
        ByteBuffer buffer = ByteBuffer.allocateDirect(total);
        buffer.put(string.getBytes("US-ASCII"));
        buffer.put(suffix.getBytes("US-ASCII"));
        buffer.flip();
        return buffer;
    }

}
